package cn.tedu.tmall.basic.service.impl;

import cn.tedu.tmall.basic.dao.cache.IDistrictCacheRepository;
import cn.tedu.tmall.basic.dao.persist.repository.IDistrictRepository;
import cn.tedu.tmall.basic.pojo.vo.DistrictSimpleVO;
import cn.tedu.tmall.basic.service.IDistrictService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 处理省市区数据的业务实现类
 *
 * @author java@tedu.cn
 * @version 3.0
 */
@Slf4j
@Service
public class DistrictServiceImpl implements IDistrictService {

    @Autowired
    private IDistrictRepository districtRepository;
    @Autowired
    private IDistrictCacheRepository districtCacheRepository;

    @Override
    public List<DistrictSimpleVO> listByParent(Long parentId) {
        // return districtRepository.listByParent(parentId);
        List<DistrictSimpleVO> cacheList = districtCacheRepository.listByParent(parentId); //换成从Redis中取数据
//        if (cacheList.size() == 0) {
//            List<DistrictSimpleVO> dbList = districtRepository.listByParent(parentId);
//            districtCacheRepository.saveList(parentId,dbList);
//            return dbList;
//        }
        return cacheList;
    }

    @Override
    public void rebuildCache() {
        districtCacheRepository.deleteAll();
        //        for (long parentId = 0L; parentId < 5000; parentId++) {  //方法1 : 死方法,直接循环不可能大于的数
//            List<DistrictSimpleVO> districtList = districtRepository.listByParent(parentId);
//            if (districtList.size() > 0) {
//                districtCacheRepository.saveList(parentId, districtList);
//            }
//        }
        Long parentId = 0L;  //先定义最大的父级ID
        List<DistrictSimpleVO> districtList = districtRepository.listByParent(parentId);
        districtCacheRepository.saveList(parentId,districtList);
        callRecursion(districtList);  //调用递归
    }

    private void callRecursion( List<DistrictSimpleVO> districtList) { //调用递归传参数
        for (DistrictSimpleVO district: districtList) {
            Long id = district.getId();
            List<DistrictSimpleVO> sunList = districtRepository.listByParent(id);
            if (sunList.size() > 0) {
                districtCacheRepository.saveList(id,sunList);
                callRecursion(sunList);
            }
        }
    }
}
